package com.fauks.gmall.passport.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.fauks.gmall.bean.UmsMember;
import com.fauks.gmall.service.UserService;
import com.fauks.gmall.util.JwtUtil;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

@Controller
public class PassportController {

    @Reference
    private UserService userService;

    @RequestMapping("index")
    public String index(String ReturnUrl, ModelMap modelMap) {
        modelMap.put("ReturnUrl", ReturnUrl);
        return "login";
    }

    /**
     * 验证token有效性
     *
     * @param token
     * @return
     */
    @ResponseBody
    @RequestMapping("verifyToken")
    public String verifyToken(String token, String ip) {
        //使用jwt解密token
        Map<String, Object> params = JwtUtil.decode(token, "fauks20200229", ip);
        //封装返回数据
        Map<String, String> result = new HashMap<>();
        if (params != null) {
            result.put("status", "success");
            result.put("memberId", (String) params.get("memberId"));
            result.put("nickName", (String) params.get("nickName"));
        } else {
            result.put("status", "fail");
        }
        return JSON.toJSONString(result);
    }

    @RequestMapping("login")
    @ResponseBody
    public String login(UmsMember umsMember, HttpServletRequest request) {
        //调用用户服务验证用户名、密码
        UmsMember memberInfo = userService.login(umsMember);
        String token = "fail";
        if (memberInfo != null) {
            //使用jwt生成token
            //如果使用nginx代理获取的是nginx的ip
            String nginxIp = request.getHeader("x-forwarded-for");
            if (StringUtils.isEmpty(nginxIp)) {
                nginxIp = request.getRemoteAddr();
            }
            if (StringUtils.isEmpty(nginxIp)) {
                nginxIp = "127.0.0.1";
            }
            Map<String, Object> params = new HashMap<>();
            params.put("memberId", memberInfo.getId());
            params.put("nickName", memberInfo.getNickname());
            //盐值一般需要md5
            token = JwtUtil.encode("fauks20200229", params, nginxIp);

            //将token存入redis
            userService.addUserToken(token, memberInfo.getId());
        }

        return token;
    }
}
